//
//  ScanBLEHelper.m
//  AFNetworking
//
//  Created by Henry on 2022/12/29.
//

#import "ScanBLEHelper.h"
#import "BlufiClient.h"
#import "Single.h"
#import "EventData.h"
#import "NVLogManager.h"
#import "DeviceUtil.h"
#import "NSString+CY.h"

typedef enum {
    ScanInit = 0,
    ScanShaking,
} ScanStatus;
#define  filterContent @"Siter"

@interface ScanBLEHelper()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property(nonatomic,strong)id<BLEScanDelegate> delegate;
@property(nonatomic, strong) NSMutableArray *array_device;

@property(nonatomic,strong)NSDictionary * productList;

// 中心管理者(管理设备的扫描和连接)
@property (nonatomic, strong) CBCentralManager *centralManager;
// 外设状态
@property (nonatomic, assign) CBManagerState peripheralState;
@property(nonatomic,assign)BOOL flag_first;
@end
@implementation ScanBLEHelper

-(instancetype)initWithDelegate:(id<BLEScanDelegate>) delegate{
    if(self = [super init]){
        self.delegate = delegate;
    }
    return self;
}

- (NSMutableArray *)array_device {
    if (!_array_device) {
        _array_device = [[NSMutableArray alloc] init];
    }
    return _array_device;
}

-(NSDictionary *)productList{
    if(_productList==nil){
        NSDictionary *dic1 = @{@"0001":@"GS368",@"0002":@"GS888W",@"0003":@"GS886W",@"1001":@"GS198"};
        _productList = [[NSDictionary alloc] initWithDictionary:dic1];
    }
    return _productList;
}



- (void)startScan{
    self.centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
    if (@available(iOS 10.0, *)) {
        if (self.peripheralState ==  CBManagerStatePoweredOn)
        {
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        }
    } else {
        // Fallback on earlier versions
        [self.centralManager scanForPeripheralsWithServices:nil options:nil];
    }
}


-(void)stop {
    self.flag_first = NO;
    [self.centralManager stopScan];
}

#pragma mark -delegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBManagerStateUnknown:{
            NVLogInfo(@"status->:未知状态");
            self.peripheralState = central.state;
            NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:1103 userInfo:nil];
            if(self.delegate && [self.delegate respondsToSelector:@selector(dueWithErr:)]){
                [self.delegate dueWithErr:error];
            }
            [self stop];
        }
            break;
        case CBManagerStateResetting:
        {
            NVLogInfo(@"status->:重置状态");
            self.peripheralState = central.state;
            if(self.delegate && [self.delegate respondsToSelector:@selector(dueWithErr:)]){
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:1103 userInfo:nil];
                [self.delegate dueWithErr:error];
            }
            [self stop];
        }
            break;
        case CBManagerStateUnsupported:
        {
            NVLogInfo(@"status->:不支持的状态");
            self.peripheralState = central.state;
            if(self.delegate && [self.delegate respondsToSelector:@selector(dueWithErr:)]){
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:1103 userInfo:nil];
                [self.delegate dueWithErr:error];
            }
            [self stop];
        }
            break;
        case CBManagerStateUnauthorized:
        {
            NVLogInfo(@"status->:未授权的状态");
            self.peripheralState = central.state;
            if(self.delegate && [self.delegate respondsToSelector:@selector(dueWithErr:)]){
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:1100 userInfo:nil];
                [self.delegate dueWithErr:error];
            }
            [self stop];
        }
            break;
        case CBManagerStatePoweredOff:
        {
            NVLogInfo(@"status->:关闭状态");
            self.peripheralState = central.state;
            if(self.delegate && [self.delegate respondsToSelector:@selector(dueWithErr:)]){
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:1009 userInfo:nil];
                [self.delegate dueWithErr:error];
            }
            [self stop];
        }
            break;
        case CBManagerStatePoweredOn:
        {
            NVLogInfo(@"status->:开启状态－可用状态");
            self.peripheralState = central.state;
            NVLogInfo(@"%ld",(long)self.peripheralState);
            if(self.delegate && [self.delegate respondsToSelector:@selector(blueToothAvailable)]){
                [self.delegate blueToothAvailable];
            }

            if(self.flag_first==NO){
                self.flag_first = YES;
                [self.centralManager scanForPeripheralsWithServices:nil options:nil];
            }
//            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        }
            break;
        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
   
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

}

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    Peripheral *device = [[Peripheral alloc] initWithPeripheral:peripheral];
    device.name = [advertisementData objectForKey:@"kCBAdvDataLocalName"];
    device.rssi = RSSI.intValue;
    
    if ([DeviceUtil shouldAddToSource:device withArrary:self.array_device]) {
        device.productKey = [self getBlueModelFromBlueName:device.name];
        [self.array_device addObject:device];
        if(self.delegate && [self.delegate respondsToSelector:@selector(blueToothFindDevice:)]){
            [self.delegate blueToothFindDevice:self.array_device];
        }
    }
}



-(NSString *)getBlueModelFromBlueName:(NSString *)bluename{
    
    if([NSString isBlankString:bluename]||bluename.length<=9){
        return nil;
    }
    
    NSRange ranage1 = [bluename rangeOfString:@"_"];
    
    if(ranage1.location == NSNotFound){
        return nil;
    }
        
    NSInteger location = ranage1.location;
    NSString *de = [bluename substringFromIndex:location+1];
    
    NSRange ranage = [de rangeOfString:@"_"];
    if(ranage.location==NSNotFound){
        return nil;
    }else{
        return [de substringToIndex:ranage.location];
    }
    
}

@end
